package fr.xebia.monitoring.export.servlet;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;

import fr.xebia.monitoring.beans.AggregatedMeasures;
import fr.xebia.monitoring.beans.formater.FormaterException;
import fr.xebia.monitoring.beans.formater.MeasureFormater;
import fr.xebia.monitoring.beans.formater.MeasureFormaterFactory;

public class MeasureGetterServlet extends AbstractMeasureAwareServlet {

	private static final long serialVersionUID = 1L;

	private static final Logger logger = Logger.getLogger(MeasureGetterServlet.class);
	
	private MeasureFormater formater;

	@Override
	public void init() throws ServletException {
		super.init();
		String format = getInitParameter("format");
		if (StringUtils.isEmpty(format)) {
			logger.info("No format specified, using xml as default");
			format = MeasureFormaterFactory.XML_FORMAT;
		}
		formater = MeasureFormaterFactory.createFormater(format);
	}

	@Override
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		response.setContentType("text/xml");
		AggregatedMeasures measures = getAggregatedMeasures();
		try {
			formater.format(measures, response.getWriter());
		} catch (FormaterException e) {
			throw new ServletException("Can't format measures", e);
		}
	}
}
